package edu.gatech.cs2340.bytebankers.presenter;

import java.awt.Point;
import java.util.LinkedList;

import edu.gatech.cs2340.bytebankers.model.Journey;
import edu.gatech.cs2340.bytebankers.model.Location;
import edu.gatech.cs2340.bytebankers.model.Trail;
import edu.gatech.cs2340.bytebankers.notifications.GameEvents;
import edu.gatech.cs2340.bytebankers.notifications.Notifier;
import edu.gatech.cs2340.bytebankers.view.IMapView;

public class MapPresenter extends Notifier implements IMapPresenter
{
	private IMapView mapView;
	private Journey journey;
	private Location lastLocation, nextLocation;
	private Trail trail;
	private Location[] locList;
	private String[] nameList;
	private Point[] pointList;
	private Point currPoint;
	private LinkedList<Location> locationList;
	private double percentTraveled, lat, lon;
	
	public MapPresenter(Journey journey)
	{
		this.journey = journey;
	}
	
	/**
	 * Method that sets the position on the map
	 * @param mapView - the map view
	 */
	public void setView(IMapView mapView)
	{
		this.mapView = mapView;
		trail = journey.getTrail();
		
		//get a list of locations from the trail
		locationList = trail.getLocationList();
		locList = new Location[locationList.size()];
		for(int x=0; x<locationList.size(); x++)
			locList[x] = locationList.get(x);
		
		//make an array of names and points from the list of locations
		nameList = new String[locationList.size()];
		pointList = new Point[locationList.size()];
		for(int x=0; x<locList.length; x++)
		{
			nameList[x] = locList[x].getName();
			pointList[x] = locList[x].getCoordinates();
		}
		
		mapView.setLocationNames(nameList);
		mapView.setLocationPoints(pointList);
		
		//get prev and next location
		lastLocation = journey.getlastLocation();
		nextLocation = lastLocation.getNextLocation();
		
		//find percentage traveled
		percentTraveled = (double)journey.getDistanceFromLastLocation()/
		(double)lastLocation.getDistanceToNext();
		
		//calculate current latitude, longitude
		lat = lastLocation.getLat() + percentTraveled * 
				(nextLocation.getLat() - lastLocation.getLat());
		lon = lastLocation.getLon() + percentTraveled * 
				(nextLocation.getLon() - lastLocation.getLon());
		
		//make current point
		currPoint = new Point();
		currPoint.x = (int)lat;
		currPoint.y = (int)lon;
		
		mapView.setCurrentPosition(currPoint);
	}
	
	public void onBackToJourneyClick()
	{
		sendNotification(GameEvents.MAP_CLOSED);
	}
}
